<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container" >
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" >
        <el-form-item label="订单号" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入订单号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="商品名称" prop="keywords">
          <el-input
            v-model="queryParams.goodsName"
            placeholder="请输入商品名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="订单状态" prop="status" >
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" style="width: 200px;">
            <el-option 
              v-for="item in status_arr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="邀请码" prop="inviteCode">
          <el-input
            v-model="queryParams.inviteCode"
            placeholder="请输入邀请码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="订单类型" prop="order_type" >
          <el-select v-model="queryParams.order_type" placeholder="请选择订单状态" style="width: 200px;">
            <el-option 
              v-for="item in order_type_arr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="来源门店" prop="shop_id" >
          <el-select v-model="queryParams.shop_id" placeholder="请选择订单状态" style="width: 200px;">
            <el-option 
              v-for="item in shop_arr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="订单来源" prop="order_source" >
          <el-select v-model="queryParams.order_source" placeholder="请选择订单状态" style="width: 200px;">
            <el-option 
              v-for="item in source_arr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="付款方式" prop="pay_type" >
          <el-select v-model="queryParams.pay_type" placeholder="请选择付款方式" style="width: 200px;">
            <el-option 
              v-for="item in pay_type_arr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createTime"
            :editable="false"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item> -->


        <el-form-item class="search-buttons">
          <el-button class="filter-item" type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>


          <el-button style="background-color: green; color: white;" @click="piliang">批量完成订单</el-button>

          <!-- <el-button  icon="download" >
            导出订单商品
          </el-button>-->
          <el-button  icon="download" @click="daochu_excel">
            导出订单
          </el-button>

          <import_excel style="margin-top: 5px;margin-left: 15px;"></import_excel>
          



        </el-form-item>

        
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <el-table
        v-loading="loading"
        :data="Lists"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="orderSn" label="订单号" width="150" />
        <el-table-column prop="orderGoods.goodsName" label="商品名称" />
        <el-table-column prop="orderGoods.goodsNum" label="商品数量" width="100" />
        <el-table-column prop="money" label="商品价格" width="100" />

        <!-- <el-table-column prop="goods_logo" label="商品图片" >
          <template #default="{ row }">
            <el-image
              style="width: 50px; height: 50px; border-radius: 50%"
              :src="row.goods_logo || 'https://xcx.yumeishangmao.com/uploads/8b112625e64da7e7dc69fab1044487e5.png'"
              :preview-src-list="[row.goods_logo]"
            />
          </template>
        </el-table-column> -->

        <el-table-column prop="expressNo" label="快递单号"/>


        <el-table-column prop="addressUser.contact" label="收货人"  />
        <el-table-column prop="addressUser.mobile" label="收货电话" />
        <el-table-column prop="addressUser.address" label="收货地址" width="200" />
        
        <!-- <el-table-column prop="remark" label="收货备注"  />

        <el-table-column prop="delivery_type" label="配送方式" width="100" />
        <el-table-column prop="shipping_fee" label="运费" width="100" /> -->

        <el-table-column prop="orderStatus" label="订单状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.orderStatus == 0" type="success">全部</el-tag>
            <el-tag v-else-if="scope.row.orderStatus == 1" type="success">待发货</el-tag>
            <el-tag v-else-if="scope.row.orderStatus == 2" type="success">待收货</el-tag>
            <el-tag v-else-if="scope.row.orderStatus == 3" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.orderStatus == 4" type="success">已关闭</el-tag>
            <el-tag v-else type="info"></el-tag>

            <!-- <el-tag v-if="scope.row.status == 1" type="success">待支付</el-tag>
            <el-tag v-else-if="scope.row.status == 2" type="success">待发货</el-tag>
            <el-tag v-else-if="scope.row.status == 3" type="success">已发货</el-tag>
            <el-tag v-else-if="scope.row.status == 4" type="success">已收货</el-tag>
            <el-tag v-else-if="scope.row.status == 5" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.status == 6" type="success">待使用</el-tag>
            <el-tag v-else-if="scope.row.status == 7" type="success">已使用</el-tag>
            <el-tag v-else-if="scope.row.status == 8" type="success">已关闭</el-tag>
            <el-tag v-else-if="scope.row.status == 9" type="success">退款中</el-tag>
            <el-tag v-else type="info"></el-tag> -->
          </template>
        </el-table-column>

        <!-- <el-table-column prop="pay_type" label="支付方式" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.pay_type == 1" type="success">余额支付</el-tag>
            <el-tag v-else type="info"></el-tag>
          </template>
        </el-table-column> -->

        <!-- <el-table-column prop="order_source" label="订单来源" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.order_source == 1" type="success">微信小程序</el-tag>
            <el-tag v-else type="info"></el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="total_amount" label="实付总金额" width="100" /> -->

        <el-table-column prop="createTime" label="创建时间" width="220" />
        <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
v-if="scope.row.orderStatus == 1"
                v-hasPerm="'order:order:delivery'"
                type="primary"
                icon="edit"
                link
                size="small"
                @click="handleOpenDialog(scope.row,1,'send')"
              >
                发货
              </el-button>


              <el-button
v-if="scope.row.orderStatus == 2"
                type="primary"
                icon="edit"
                link
                size="small"
                @click="handleClose(scope.row.id,3)"
              >   
                完成订单  
              </el-button>
              
                            <el-button
v-if="scope.row.orderStatus == 3"
                type="primary"
                icon="edit"
                link
                size="small"
                @click="handleClose(scope.row.id,4)"
              >   
                关闭订单  
              </el-button>


              <el-button
                v-hasPerm="'order:order:edit'"
                type="primary"
                icon="edit"
                link
                size="small"
                @click="handleOpenDialog(scope.row,1,'edit')"
              >
                修改快递单号
              </el-button>
              
            </template>
        </el-table-column>
      </el-table>

      <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="formData"  label-width="120px">
        
        <el-form-item v-if="str == 2" label="订单号" prop="order_no">
          <el-input v-model="formData.order_no" :disabled="true" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item v-if="str == 2" label="收货人" prop="consignee">
          <el-input v-model="formData.consignee" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item v-if="str == 2" label="收货电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入收货人电话" />
        </el-form-item>
        <el-form-item v-if="str == 2" label="收货地址" prop="address">  
          <el-input v-model="formData.address" placeholder="请输入收货人地址" />
        </el-form-item>
        <el-form-item v-if="str == 2" label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" />   
        </el-form-item>

        <el-form-item v-if="str == 1" label="快递单号" prop="expressNo">
          <el-input v-model="formData.expressNo" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="days"  label-width="220px">
        
        <el-form-item  label="处理发货时间大于N天的订单" prop="days">
          <el-input v-model="days"  placeholder="请输入天数" />
        </el-form-item>
        </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit2">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "订单",
  inheritAttrs: false,
});

import OrderAPI, { OrderVO,OrderForm } from "@/api/system/order.api";
import { ElMessageBox } from 'element-plus'
import import_excel from "./import_excel.vue";
const queryFormRef = ref();
const FormRef = ref();

const dialog = reactive({
  title: "",
  visible: false,
});

const days = ref(7);
const dialog2 = reactive({
  title: "批量完成订单",
  visible: false,
});

function handleSubmit2() {
  if (days.value <= 0) {
    ElMessageBox.alert("请输入大于0的天数", "提示", {
      confirmButtonText: "确定",
      type: "warning",
    });
    return;
  }
  loading.value = true;
  //大于N天
  OrderAPI.Order_COMPLETE_URL({"days": days.value })
    .then(() => {
      ElMessage.success("批量完成订单成功");
      handleCloseDialog();
      handleQuery();
    })
    .finally(() => (loading.value = false));
}


const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<any>({
  keywords: "",
  status: 0,
  order_type:0,
  shop_id: 0,
  order_source: 0,
  pageNum: 1,
  pageSize: 10,
  goodsName: "",
  inviteCode: "",
});

const formData = reactive<OrderForm>({
  /** ID(新增不填) */
  id: '0',
  /** 订单号 */
  order_no: '',
  /** 收货人 */
  consignee: '',
  /** 收货人电话 */
  phone: '',
  /** 收货人地址 */
  address: '',
  /** 备注 */
  remark: '',
  /** 快递单号 */
  expressNo: '',
});

 // 1-待发货;2-待收货;3-已完成;4-已关闭
const status_arr = ref([
  { value: 0, label: "全部" },
  { value: 1, label: "待发货" },
  { value: 2, label: "待收货" },
  { value: 3, label: "已完成" },
  { value: 4, label: "已关闭" }
]);

// const status_arr = ref([
//   { value: 0, label: "全部" },
//   { value: 1, label: "待支付" },
//   { value: 2, label: "待发货" },
//   { value: 3, label: "已发货" },
//   { value: 4, label: "已收货" },
//   { value: 5, label: "已完成" },
//   { value: 6, label: "待使用" },
//   { value: 7, label: "已使用" },
//   { value: 8, label: "已关闭" },
//   { value: 9, label: "退款中" },
// ]);

// const order_type_arr = ref([
//   { value: 0, label: "全部" },
//   { value: 1, label: "普通订单" },
//   { value: 2, label: "拼团订单" },
// ]);

// const shop_arr = ref([
//   { value: 0, label: "全部" },
//   { value: 1, label: "门店1" },
//   { value: 2, label: "门店2" },
// ]);

// const source_arr = ref([
//   { value: 0, label: "全部" },
//   { value: 1, label: "微信小程序" },
// ]);

// const pay_type_arr = ref([
//   { value: 0, label: "全部" },
//   { value: 1, label: "余额支付" },
// ]);

const Lists = ref<OrderVO[]>();
const total = ref(0);

// 查询
function handleQuery() {
  console.log(queryParams)
  loading.value = true;
  total.value = 15

  OrderAPI.getOrderList(queryParams)
    .then((res) => {
      Lists.value = res.data;
      total.value = res.total;
    })
    .catch((error) => {
      console.error("查询订单失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

const str = ref(0);
const strTypes = ref();
function handleOpenDialog(data: OrderVO,type: number, strType?: string) {
  strTypes.value = strType
  dialog.visible = true;
  formData.id = data.id;
  str.value = type;
  dialog.title = "修改";
  Object.assign(formData, data);
}

function daochu_excel() {
  OrderAPI.export_excel().then((res) => {
    // 确保字符串以UTF-8 BOM开头，解决Excel中文乱码问题
    const BOM = '\uFEFF';
    const content = BOM + res;
    
    // 创建Blob对象
    const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    const filename = `订单记录_${new Date().toISOString().slice(0, 10)}`;

    link.href = url;
    link.download = `${filename}.csv`;
    link.style.visibility = 'hidden';
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    URL.revokeObjectURL(url);


  }).catch((error) => {
    console.error("导出失败:", error);
  });
}

// 提交表单
function handleSubmit() {
  if(strTypes.value=='send'){
    FormRef.value.validate((valid: any) => {
    if (valid) {
        loading.value = true;
        console.log("提交表单数据", formData);
        const dataJson = {
          dataId:formData.id,
          expressNo: formData.expressNo,
        }
        OrderAPI.update(dataJson)
          .then(() => {
            ElMessage.success("操作成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    });
  }else{
    FormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        console.log("提交表单数据", formData);
        const dataJson = {
          dataId:formData.id,
          expressNo: formData.expressNo,
        }
        OrderAPI.Order_odd_URL(dataJson)
          .then(() => {
            ElMessage.success("操作成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    });
  }
  
}

const handleClose = async (id:any,type:number) => {
  try {
    await ElMessageBox.confirm(
      '确定要执行此操作吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // 用户点击了确定
    const dataJson = {
      dataId:id,
      orderState: type,
    }
    OrderAPI.closeOrder(dataJson)
      .then(() => {
        ElMessage.success("订单已关闭");
        handleQuery();
      })
      .catch((error) => {
        ElMessage.error("关闭订单失败: " + error.message);
      });
  } catch (error: any) {
    // 用户点击了取消
    console.log('操作已取消'+error)
  }
}



// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  dialog2.visible = false;

  resetForm();
}

function piliang(){
  dialog2.visible = true;
}

// 重置表单
function resetForm() {
  FormRef.value.resetFields();
  FormRef.value.clearValidate();
}

onMounted(() => {
  handleQuery();
});
</script>
